/*
 * @Author: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @Date: 2025-06-24 11:01:14
 * @LastEditors: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @LastEditTime: 2025-08-31 10:19:55
 * @FilePath: /server/workspace/src/base/thread.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

#include "thread.h"
#include"Log.h"
#include<atomic>
namespace Yizhi{
    thread_local std::string thread_name("unkown");
    std::atomic<uint64_t> Thread_Count{0};
    thread_local int t_thread_id=0;
    static Logger::ptr g_logger=SERVER_LOG_NAME("system");


    /// @brief 带参构造函数
    /// @param cb 回调函数 
    /// @param name 自定义线程名
    Thread::Thread(CallbackType cb,std::string name)
    :m_cb(cb)
    ,m_name(name)
    ,m_id(-1)
    ,m_sem(0){
        setDefaultName();
        int rt=pthread_create(&m_thread,nullptr,&Thread::run,this);
        if(rt){
            SERVER_LOG_ERROR(g_logger)<<"pthread_create error";
            throw std::logic_error("pthread create error");
        }
        m_sem.wait();
    }

    /// @brief pthread_join封装
    void Thread::join(){
        if(m_thread){
            int rt=pthread_join(m_thread,nullptr);
            if(rt){
                SERVER_LOG_ERROR(g_logger)<<"Thead join error";
                throw std::logic_error("thread join error");
            }
            m_thread=0;
        }
       
    }
    
    /// @brief 当m_name为空，设置默认name
    void Thread::setDefaultName(){
        auto number=Thread_Count++;
        if(m_name.empty()){
            char buf[32];
            sprintf(buf,"Thread%ld",number);
            m_name=buf;
        }

    }

    /// @brief 返回当前线程id
    /// @return 当前线程id. 
    int Thread::GetTid(){
        if(t_thread_id==0){
            return Yizhi::GetThreadid();
        }
        return t_thread_id;
    }

    /// @brief 线程入口函数，执行回调函数
    /// @param arg this指针 
    /// @return nullptr
    void* Thread::run(void * arg){

       Thread* self=static_cast<Thread*> (arg);
       thread_name=self->m_name;
       self->m_id=GetThreadid();//当开始执行时，才获得线程号
       t_thread_id=self->m_id;//记录当前线程id;
       CallbackType cb;
       cb.swap(self->m_cb);
       self->m_sem.post();
       try{
            cb();
       }
       catch(std::exception &e){

       }
       catch(...){

       }
       return nullptr;
    }


    const std::string& Thread::getName(){
        return thread_name;
    }

    /// @brief 析构函数，当当前线程仍为退出，挂到后台执行
    Thread::~Thread(){
        if(m_thread){
            int rt =pthread_detach(m_thread);
            if(rt){
                SERVER_LOG_ERROR(g_logger)<<"pthread_detach error";
                //throw std::logic_error("pthread_detach error");
            }
        }
    }

    
    

}